const { mock } = require("mockjs");
const jwt = require("jsonwebtoken"); 
const _ = require("lodash");
const UUID = require("uuid");
class Utils {
  constructor(collName) {
    this.coll = collName;
  }

  uuid() {
    return UUID.v1().replace(/-/g, "");
  }

  /**
   * 过滤列表
   * @param {*} obj 要过滤的属性
   */
  filterList(list, attrObj) {
    let newList = list;
    for (let key in attrObj) {
      let value = attrObj[key];
      if (typeof value !== "boolean") {
        // vale值为undefined或者'all'的不进行过滤
        if (!!value && value !== "all") {
          newList = filterFn(key);
        }
      } else {
        // 布尔类型执行判断
        newList = filterFn(key);
      }
    }

    function filterFn(key) {
      // 值带有key
      if (key.includes("key")) {
        // 原来的key
        let originkey = key.slice(0, -3);
        return newList.filter((item) => item[originkey].includes(attrObj[key]));
      } else {
        return newList.filter((item) => item[key] === attrObj[key]);
      }
    }
    return newList;
  }

  /**
   * 添加token
   * @param {object} userInfo
   */
  getToken(userInfo) {
    let secret = "finance"; // 指定密钥
    // 生成token
    let token = jwt.sign(userInfo, secret, {
      expiresIn: "5s",
    });
    return token;
  }

  log() {
    console.info("<----------- " + this.coll + " ----------->");
    for (let i = 0; i < arguments.length; i++) {
      console.info(arguments[i]);
    }
    console.info("<----------- " + this.coll + " ----------->");
  }

  /**
   *
   * @param {*} data 返回的数据
   * @param {*} name 数据名称
   */
  handleSuccess(data) {
    return {
      code: 200,
      msg: "success",
      data,
    };
  }

  handleError(error) {
    const errorCode = {
      604: "对象不存在",
      601: "字段校验失败",
      600: "其他错误",
    };

    let { code = 600, message, name } = error;
    if (name === "ValidationError") {
      code = 601;
      let str = message.match(/`.*?`/);
      message = "缺少" + str[0];
    }

    return {
      code: code,
      msg: message,
    };
  }
}

module.exports = Utils;
